'use strict';
/*
 * date@2018-08-23
 * author@杨道泉
 * define@本插件用于通用读取店铺内的商品，并予以打折
 * activeType="limit"开启限购类型
 * showDepot={true} 显示仓库商品
 * maxSelect={1} 最多能加入的个数
 */
import React,{PropTypes} from 'react'; 
import {Select,Tab,Tag,Loading,Pagination,Search,Dialog,Input,Checkbox,Button} from 'qnui';
import { Row, Col } from 'qnui/lib/grid';
import classnames from 'classnames';
import {ajax } from 'utils/index';
import './index.scss';
const TabPane = Tab.TabPane;
	
class GoodsItemsZhekou extends React.Component {

	constructor(props) {
        super(props);
        this.state = {
        		items:[],
        		seller_cats:[],
        		is_onsale:true,
        		q:"",
        		total_results:0,
        		page:1,
        		pagesize:10,
        		selected_items:[],
        		dialogVisible:false,
        		showTabEx:true,
        		setItems:[],
           };
    }
	componentWillMount(){
		this.getItemsOnSale({
			page:1,
			pagesize:10,
			cids:"",
			q:""
		});
		this.getSellerCats({
			nick:window.info.user_nick
		});
	}
	componentWillReceiveProps(nextProps){

	}
	componentDidUpdate(){

	}
	componentDidMount(nextProps){
		this.setState({selected_items:this.props.selectedItems?this.props.selectedItems:[]});
	}
	getItemsOnSale(params){
		this.setState({is_onsale:true});
		if(window.workbench){
			//千牛环境执行创建折扣,含有workbench参数为千牛环境
			  window.QN.top.invoke( {
					cmd : 'taobao.items.onsale.get',
					param : params,
					method:"post",
					success : function(rsp, cmd, param) {
						console.log(rsp,param);
					},
					error : function(msg, cmd, param) {
						console.log(msg,param);
					}
				} );
		}else{
			ajax({
			  api: 'getItemsOnSale',
			  method: 'GET',
			  data:params
			},(json) => {
				if(json.total_results>0){
					if(!(json.items.item instanceof Array)){
						json.items.item = Array(json.items.item);
					}
				}else{
					json.items={item:[]};
				}
				this.setState({
					  items:json.items.item,
					  total_results:parseInt(json.total_results),
					  page:params.page,
					  pagesize:params.pagesize,
					  cids:params.cids,
					  q:params.q,
					  selectAll:false
					});
			},(json) =>{
				const login = (json.code==210);
				this.setState({
					message:json.msg+(json.sub_msg?json.sub_msg:""),
					loginFalse:login,
					showErrorDialog:true
				});
			});
			
		}
	}
	getItemsIndepot(params) {
		this.setState({is_onsale:false});
			if(window.workbench){
				//千牛环境执行创建折扣,含有workbench参数为千牛环境
				  window.QN.top.invoke( {
						cmd : 'taobao.items.inventory.get',
						param : params,
						method:"post",
						success : function(rsp, cmd, param) {
							console.log(rsp,param);
						},
						error : function(msg, cmd, param) {
							console.log(msg,param);
						}
					} );
			}else{
				ajax({
				  api: 'getItemsIndepot',
				  method: 'GET',
				  data:params
				},(json) => {
					if(json.total_results>0){
						if(!(json.items.item instanceof Array)){
							json.items.item = Array(json.items.item);
						}
					}else{
						json.items={item:[]};
					}
					
					this.setState({
					  items:json.items.item,
					  total_results:parseInt(json.total_results),
					  page:params.page,
					  pagesize:params.pagesize,
					  cids:params.cids,
					  q:params.q,
					  selectAll:false
					});
				},(json) =>{
					const login = (json.code==210);
					this.setState({
						message:json.msg+(json.sub_msg?json.sub_msg:""),
						loginFalse:login
					});
				});
				
			}
		}

/*
 * @params {nick："用户昵称"}
 */
getSellerCats(params){
		if(window.workbench){
			//千牛环境执行创建折扣,含有workbench参数为千牛环境
			  window.QN.top.invoke( {
					cmd : 'taobao.sellercats.list.get',
					param : params,
					method:"post",
					success : function(rsp, cmd, param) {
						console.log(rsp,param);
					},
					error : function(msg, cmd, param) {
						console.log(msg,param);
					}
				} );
		}else{
			ajax({
			  api: 'getSellerCats',
			  method: 'GET',
			  data:params
			},(json) => {
				if(json.seller_cats && !(json.seller_cats.seller_cat instanceof Array)){
					json.seller_cats.seller_cat = Array(json.seller_cats.seller_cat);
				}
				this.setState({
				  seller_cats:json.seller_cats.seller_cat
				});
			},(json) => {
				const login = (json.code==210);
				this.setState({
					message:json.msg+(json.sub_msg?json.sub_msg:""),
					loginFalse:login
				})
			});
		}
	}
onCatChange(cat_id){
	if(this.state.is_onsale){
		this.getItemsOnSale({
				page:this.state.page,
				pagesize:this.state.pagesize,
				cids:cat_id,
				q:this.state.q
		});
	}else{
		this.getItemsIndepot({
			page:this.state.page,
			pagesize:this.state.pagesize,
			cids:cat_id,
			q:this.state.q
		});
	}
}
onSearchItem(key){
	this.setState({q:key.key});
	if(this.state.is_onsale){
		this.getItemsOnSale({
				page:this.state.page,
				pagesize:this.state.pagesize,
				cids:this.state.cids,
				q:key.key
		});
	}else{
		this.getItemsIndepot({
			page:this.state.page,
			pagesize:this.state.pagesize,
			cids:this.state.cids,
			q:key.key
		});
	}
}
onTabChange(key){
	this.setState({is_onsale:key=="onSale",showTabEx:true});
	switch(key){
		case "onSale":
			this.getItemsOnSale({
					page:this.state.page,
					pagesize:this.state.pagesize,
					cids:this.state.cids,
					q:this.state.q
			});
			break;
		case "inDepot":
			this.getItemsIndepot({
				page:this.state.page,
				pagesize:this.state.pagesize,
				cids:this.state.cids,
				q:this.state.q
			});
			break;
		case "onSelected":
			this.setState({items:this.state.selected_items,total_results:0,showTabEx:false});
			break;
	}
}
onPageChange(page){
	this.setState({page:page});
	if(this.state.is_onsale){
		this.getItemsOnSale({
				page:page,
				pagesize:this.state.pagesize,
				cids:this.state.cids,
				q:this.state.q
		});
	}else{
		this.getItemsIndepot({
			page:page,
			pagesize:this.state.pagesize,
			cids:this.state.cids,
			q:this.state.q
		});
	}
}
onSelectItem(item){
	const selected = this.state.selected_items;

	let has=false;
	selected.map((s_item,key)=>{
		if(s_item.num_iid==item.num_iid){
			has=true;
			selected.splice(key,1);
		}
	});
	
	if(selected.length>=this.props.maxSelect){
		this.setState({dialogVisible:true});
		return;
	}
	
	if(!has){
		selected.push(item);
	}
	this.setState({selected_items:selected});
	this.props.getSelectItems(selected);
}
onDialogClose(){
	this.setState({dialogVisible:false});
}
changePrice(ztype,item,value){
	if(ztype=="finalPrice"){
		ztype = "decreaseAmount";
		value = (item.price - value);
	}
	let finaPrice = item.price;
	switch(ztype){
		case "decreaseAmount":
			item.promotion_type=0;
			finaPrice = item.price - value;
		break;
		case "discountRate" :
			item.promotion_type=1;
			finaPrice = item.price * (value/10);
		break;
	}
	item.finaPrice = finaPrice;
	item.value = value;
	item.ztype = ztype;
	item.promotion_value = value;
	const setItems = this.state.setItems;
	setItems[item.num_iid]=item;
	this.setState({setItems});
}
changeLimit(item,value){
	item.is_limit_buy = true;
	item.limit_buy_count = value;
	item.value = item.value?item.value:0;
	const setItems = this.state.setItems;
	setItems[item.num_iid]=item;
	this.setState({setItems});
}
handleItemOnClick(item){
	let select_items = this.state.selected_items;
		let hasItem = -1;
		select_items.map((i,k)=>{
			if(i.num_iid==item.num_iid){
				hasItem=k;
			}
		})
		if(hasItem<0){
			select_items.push(item);
		}else{
			select_items.splice(hasItem,1);
		}
		this.setState({selected_items:select_items});
}
changeSelectAllItems(checked){
	const items = this.state.items;
	const setItems = this.props.setDoneItems;
	const selected_items = this.state.selected_items;
	if(checked){
		items.map(item=>{
			let has = false;
			selected_items.map(sitem=>{
				if(sitem.num_iid==item.num_iid){
					has = true;
					return;
				}
			});
			
			if(!has && (!setItems[item.num_iid] || setItems[item.num_iid].status!="done")){
				selected_items.push(item);
			}
		});
		this.setState({selected_items,selectAll:true});
	}else{
		items.map(item=>{
			let index = -1;
			selected_items.map((sitem,key)=>{
				if(sitem.num_iid==item.num_iid){
					index=key;
					delete selected_items[key];
					return;
				}
			});
			//selected_items.splice(index,1);
		});

		for(var i=0,len=selected_items.length;i<len;i++){ 
			if(!selected_items[i]||selected_items[i]==''||selected_items[i] === undefined){ 
				selected_items.splice(i,1); 
				len--; 
				i--; 
			} 
		}
		this.setState({selected_items,selectAll:false});
	}
}

addItemToActive(num_iid){
	if(!this.state.setItems[num_iid]){
		Dialog.alert({content:"请设置折扣！"});
		return;
	}
	if(this.props.setDoneItems[num_iid] && this.props.setDoneItems[num_iid].status=="done"){
		Dialog.alert({content:"已经设置过了！"});
		return;
	}
	this.props.addItemToActive(this.state.setItems[num_iid]);
}
addAllSelectedItemsToActive(){
	if(this.state.setItems.length>this.props.maxSelect){
		this.setState({dialogVisible:true});
		return;
	}
	if(this.state.selected_items.length==0){
		Dialog.alert({content:"您没有选择任何商品！"});
		return;
	}
	let setItems = this.state.setItems;
	let selected_items = [];
	for(let i=0;i<this.state.selected_items.length;i++){
		selected_items[this.state.selected_items[i].num_iid]=this.state.selected_items[i];
		if(this.state.zType=="discountRate"){
			selected_items[this.state.selected_items[i].num_iid].promotion_type=1;
			selected_items[this.state.selected_items[i].num_iid].promotion_value=this.state.discountRate;
			selected_items[this.state.selected_items[i].num_iid].value=this.state.discountRate;
		}else{
			selected_items[this.state.selected_items[i].num_iid].promotion_type=0;
			selected_items[this.state.selected_items[i].num_iid].promotion_value=this.state.decreaseAmount;
			selected_items[this.state.selected_items[i].num_iid].value=this.state.decreaseAmount;
		}
		selected_items[this.state.selected_items[i].num_iid].ztype=this.state.zType;
		selected_items[this.state.selected_items[i].num_iid].is_limit_buy=this.state.limitCount>0?true:false;
		selected_items[this.state.selected_items[i].num_iid].limit_buy_count=this.state.limitCount;
		setItems[this.state.selected_items[i].num_iid]=selected_items[this.state.selected_items[i].num_iid];
	}
	this.setState({setItems,selected_items:[]});
	this.props.addItemsToActive(selected_items);
}
    render() {
    		const setDoneItems = this.props.setDoneItems;
			const setItems = this.state.setItems;
    	   const loading = this.state.items.length==0?<div>没有任何商品...</div>:"";
    	   const settingAll = this.state.items.length>0?"block":"none";
    	   const items = this.state.items.map((item,key)=>{
									let finaPrice = "";
									if(setItems[item.num_iid]){
										if(setItems[item.num_iid].finaPrice){
											finaPrice = setItems[item.num_iid].finaPrice;
										}else if(setItems[item.num_iid].ztype=="discountRate"){
											finaPrice = item.price*(parseInt(setItems[item.num_iid].value)/10)
										}else{
											finaPrice = item.price-(parseInt(setItems[item.num_iid].value))
										}
									}
									let isSelected = false;
									this.state.selected_items.map(sitem=>{
										if(sitem.num_iid==item.num_iid){
											isSelected=true;
											return;
										}
									});
									const decreaseAmount = (setItems[item.num_iid] && setItems[item.num_iid].ztype=="decreaseAmount")?setItems[item.num_iid].value:"";
									const discountRate = (setItems[item.num_iid] && setItems[item.num_iid].ztype=="discountRate")?setItems[item.num_iid].value:"";
									const settingDone = (setDoneItems[item.num_iid] && setDoneItems[item.num_iid].status=="done");
									const limitCount = ((setItems[item.num_iid] && setItems[item.num_iid].is_limit_buy=="1")?setItems[item.num_iid].limit_buy_count:"");
									const bindItem = setItems[item.num_iid]?setItems[item.num_iid]:item;
									const limitBuy = this.props.activeType=="limit"?
														<Input 
															disabled={settingDone}
															style={{width:"120px"}}
															size="large" 
															addonBefore="限"
															value={limitCount}
															onChange={this.changeLimit.bind(this,bindItem)}
															addonAfter="件" 
														/>:"";
									const decrease = 	<Input 
															disabled={settingDone}
															style={{width:"120px"}}
															size="large" 
															addonBefore="减"
															state={(setItems[item.num_iid] && setItems[item.num_iid].ztype=="decreaseAmount")?"success":""}
															onChange={this.changePrice.bind(this,"decreaseAmount",bindItem)}
															value={decreaseAmount}
															addonAfter="元" 
														/>;
									const discount = 	<Input 
															disabled={settingDone}
															style={{width:"120px"}}
															size="large" 
															addonBefore="打" 
															state={item.ztype=="discountRate"?"success":""}
															onChange={this.changePrice.bind(this,"discountRate",bindItem)}
															value={discountRate}
															addonAfter="折" 
														/>;													
			   					return (
		    				   				<Row key={item.num_iid} align="center" style={{padding:0,margin:"5px 0",borderBottom:"1px dashed #CCCCCC"}}>
													<Col fixedSpan="1">
														<Checkbox onChange={this.handleItemOnClick.bind(this,item)} disabled={settingDone} checked={isSelected} id={item.num_iid} value={item.num_iid}></Checkbox>
													</Col>
													<Col fixedSpan="5">
														<a href={"https://item.taobao.com/item.htm?id="+item.num_iid} target="_blank"><img style={{border:"1px solid #C7C7C7"}} src={item.pic_url+"_80x80q90.jpg_.webp"} /></a>
													</Col>
													<Col span="4">
														<span><a href={"https://item.taobao.com/item.htm?id="+item.num_iid} target="_blank">{item.title}</a></span>
													</Col>
													<Col>
														<div className="price_number" style={{fontWeight:"bold",width:"70px",float:"left",textAlign:"right",lineHeight:"32px"}}>{item.price}</div>&nbsp;
														{discount}&nbsp;
														{decrease}&nbsp;
														{limitBuy}&nbsp;
														<Input 
															disabled={settingDone}
															style={{width:"70px"}}
															size="large" 
															placeholder="折后价"
															onChange={this.changePrice.bind(this,"finalPrice",bindItem)}
															value={finaPrice}
														/>
													</Col>
													<Col fixedSpan="5">
														<Button onClick={this.addItemToActive.bind(this,item.num_iid)}>加入活动</Button>
													</Col>
												</Row>
											);
								});

    	   const depot = this.props.showDepot?<TabPane tab="仓库中的商品" key="inDepot">
												<Row type="wrap"  justify="start"  style={{maxHeight:"400px",overflowY:"auto"}}>
												{loading}
												{
													items
												}
												</Row>
											   </TabPane>
											   :"";
		  const extraContent=this.state.showTabEx?<Row type="wrap"  justify="start" >
											<Select placeholder="选择类别" onChange={this.onCatChange.bind(this)}>
													<Option value="0">所有类别</Option>
													{
														this.state.seller_cats.map((cat,key)=>{
															 return (<Option key={key} value={cat.cid}>{cat.name}</Option>);
														})
													}
										    </Select>
								    	&nbsp;
								    <Search
								        type="搜索"
								        inputWidth={200}
								        placeholder="输入关键字"
								    	onSearch={this.onSearchItem.bind(this)}/>
									</Row>:"";
        const setAll = <Row type="wrap"  justify="start" style={{background:"#F6F6F6",lineHeight:"45px",marginTop:"10px",display:settingAll}}>
									<Col fixedSpan="6">
										<Checkbox checked={this.state.selectAll} onChange={this.changeSelectAllItems.bind(this)}>全选</Checkbox>
									</Col>
									<Col  span="4">
									</Col>
									<Col>
										<div style={{color:"#999",width:"70px",float:"left",textAlign:"right"}}>批量设置</div>&nbsp;
										<Input 
											style={{width:"120px"}}
											size="large" 
											addonBefore="打" 
											state={this.state.zType=="discountRate"?"success":""}
											onClick={()=>{this.setState({zType:"discountRate",decreaseAmount:""});}}
											onChange={(val)=>{this.setState({discountRate:val})}}
											value={this.state.discountRate}
											ref="allDiscountRate"
											addonAfter="折" 
										/>&nbsp;
										<Input 
											style={{width:"120px"}}
											size="large" 
											addonBefore="减"
											state={this.state.zType=="decreaseAmount"?"success":""}
											onClick={()=>{this.setState({zType:"decreaseAmount",discountRate:""});}}
											onChange={(val)=>{this.setState({decreaseAmount:val})}}
											value={this.state.decreaseAmount}
											ref="allDecreaseAmount"
											addonAfter="元" 
										/>&nbsp;
										{this.props.activeType=="limit"?
										<Input 
											style={{width:"120px"}}
											size="large" 
											addonBefore="限"
											value={this.state.limitCount}
											onChange={(val)=>{this.setState({limitCount:val})}}
											addonAfter="件" 
										/>:""}
									</Col>
									<Col fixedSpan="5">
										<Button type="primary" onClick={this.addAllSelectedItemsToActive.bind(this)}>批量设置</Button>
									</Col>
								</Row>;
			return (
        	 <div>
        			<Dialog visible={this.state.dialogVisible}
		                onOk={this.onDialogClose.bind(this)}
		                closable="esc,mask,close"
		                onCancel={this.onDialogClose.bind(this)}
		                onClose={this.onDialogClose.bind(this)} title="注意">
		            <h3>添加商品出错！你最多添加{this.props.maxSelect}个商品到当前活动中！</h3>
		        </Dialog>
				<Tab onChange={this.onTabChange.bind(this)} tabBarExtraContent={extraContent}>
					<TabPane tab="出售中的商品" key="onSale">
						{setAll}
						<Row type="wrap"  justify="start"  style={{maxHeight:"600px",overflowY:"auto"}}>
						{loading}
						{
							items
						}
						</Row>
				   </TabPane>
				   {
					   depot
				   }
				   <TabPane tab="已选择的商品" key="onSelected">
				   {setAll}
					<Row type="wrap"  justify="start"  style={{maxHeight:"600px",overflowY:"auto"}}>
					{loading}
					{
						items
					}
					</Row>
			   </TabPane>
				</Tab>

				<Row>
					<Pagination defaultCurrent={1} total={this.state.total_results} pageSize={this.state.pagesize} onChange={this.onPageChange.bind(this)} />,
				</Row>
			</div>
        );
    }
    
}
export default GoodsItemsZhekou;